//
//  SubmitOrderController.m
//  ios-supplier
//
//  Created by Benlai on 15/8/3.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "SubmitOrderController.h"
#import "submitOrderCell1.h"
#import "SubmitOrderCell2.h"
#import "SubmitOrderCell3.h"
#import "SubmitOrder4.h"
#import "SubmitOrderCell5.h"

#import "MemoryData.h"
#import "JFBOrderGoodsProductDS.h"
#import "JFBStoreInfo.h"
#import "JFBStoreInfoDS.h"
#import "OrderGoodsDetailController.h"
#import "SelecctAddressDS.h"
#import "MemoryData.h"
#import "ApiWareHouseID.h"
@interface SubmitOrderController ()<UIGestureRecognizerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalGoodsNumber;

@property (nonatomic, strong)UITableView *orderInfoTable;
@property (nonatomic, strong)NSArray *orderInfoArray;
@property (nonatomic, strong) SelecctAddressDS *addressModel;
@property (nonatomic, strong)JFBSubmitOrderDS *orderDetailInfo;
@property (nonatomic, strong)NSString *beizhuStr;
@property (nonatomic, strong)NSString *invoiceStr;
///供应商ID
@property (nonatomic,assign) NSInteger supplierId;
///供应商名称
@property (nonatomic,  copy) NSString *supplierName;
///供应商联系人姓名
@property (nonatomic,  copy) NSString *contactPerson;
///供应商联系电话
@property (nonatomic,  copy) NSString *contactPhone;


- (IBAction)submitOrderBtn:(id)sender;
@end

@implementation SubmitOrderController
-(void)viewWillAppear:(BOOL)animated{
    [self requestWareHouseID];//请求仓库ID
}
#pragma mark -请求仓库ID
-(void)requestWareHouseID{
    [[[ApiWareHouseID alloc]initWIthUt:[UserInfo currentUser].ut andWithWarehouseId:[[UserInfo currentUser].merchantID integerValue] andWithLimitClauseCount:0 andWithLimitClauseStart:0]startWithCompletionSuccess:^(id JSON, YTKBaseRequest *request) {
        NSLog(@"%@",JSON);
        if ([JSON[@"code"] integerValue] == 0) {
            NSDictionary *subDic = JSON[@"data"];
            if (![[subDic valueForKey:@"rows"]isEqual:[NSNull null]]) {
                NSArray *dataArray = [subDic valueForKey:@"rows"];
                NSDictionary *rows = [dataArray objectAtIndex:0];
                self.supplierId = [rows[@"supplierId"] integerValue];
                self.supplierName = rows[@"supplierName"];
                self.contactPerson = rows[@"contactPerson"];
                self.contactPhone = rows[@"contactPhone"];
            }else{
                
            }
        }else if ([JSON[@"code"] integerValue] == 99){
            UIViewController* viewController;
            UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            viewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"Login"];
        }else{
            
        }
    } failure:^(YTKBaseRequest *request) {
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.orderInfoArray = [[NSMutableArray alloc] init];
    self.addressModel = [[SelecctAddressDS alloc] init];

    self.orderInfoTable = [[UITableView alloc]initWithFrame: CGRectMake(0, TopSizeFix, self.view.frame.size.width, self.view.frame.size.height - TopSizeFix - 49) style:UITableViewStyleGrouped];
    self.orderInfoTable.delegate = self;
    self.orderInfoTable.dataSource = self;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self.orderInfoTable setSeparatorStyle: UITableViewCellSeparatorStyleNone];
    self.orderInfoTable.showsVerticalScrollIndicator = NO;
    
    self.orderInfoTable.sectionFooterHeight = 0;
    [self.view addSubview: self.orderInfoTable];
    
    self.orderInfoArray = [MemoryData sharedMemoryData].shoppingCarList;
    double totalPrice = [[MemoryData sharedMemoryData] getTotalPrice];
    NSInteger totalNumber = [[MemoryData sharedMemoryData] getCarGoodsNumber];
    
    self.totalPriceLabel.text = [NSString stringWithFormat: @"￥%.2f", totalPrice];
    self.totalGoodsNumber.text = [NSString stringWithFormat: @"(共%ld件)", (long)totalNumber];
    
    [self storeInfoSet];
    self.beizhuStr = @"";
    self.invoiceStr = @"";
    
    
    [self.navigationItem setLeftBarButtonItem:[self createBackView]];
}


- (UIBarButtonItem *)createBackView
{
    UIButton *leftButtonItem = [UIButton buttonWithType:UIButtonTypeCustom];
    
    leftButtonItem.frame = CGRectMake(0, 0, 11, 20);
    
    [leftButtonItem setBackgroundImage:[UIImage imageNamed:@"icon-Back"] forState:UIControlStateNormal];
    
    [leftButtonItem setImageEdgeInsets: UIEdgeInsetsMake((19 - 11) / 2, 0, (19 - 11) / 2, 0)];
    
    [leftButtonItem addTarget:self action:@selector(leftButtonItemClicked) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:leftButtonItem];
    
    return item;
}

-(void)leftButtonItemClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)storeInfoSet
{
    JFBGlobalSetting * setting = [JFBGlobalSetting getSetting];
    
    [JFBStoreInfoDS loadStoreInfo:^(JFBStoreInfoDS *storeInfo, NSError *error) {

        self.addressModel.receiver = storeInfo.masterName;
        self.addressModel.receiver_phone = storeInfo.masterMobile;
        self.addressModel.address_name = storeInfo.storeAddress;
        self.addressModel.ID = NSNotFound;
    } storeID:setting.shopId];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section != 2) {
        return 1;
    }
    return self.orderInfoArray.count + 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        return 80;
    }
    if ((indexPath.section == 2 && indexPath.row == self.orderInfoArray.count + 1))
    {
        return 60;
    }
    return 44;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 2) {
        return 44;
    }
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    if(indexPath.section == 0)
    {
        NSArray *arr = [[NSBundle mainBundle] loadNibNamed: @"submitOrderCell1" owner: nil options: nil];
        cell = [arr objectAtIndex: 0];
        
        submitOrderCell1 *storeInfoCell = (submitOrderCell1*) cell;
        storeInfoCell.storeNameLabel.text = [NSString stringWithFormat: @"%@(%@)", [UserInfo currentUser].shopkeeper, [UserInfo currentUser].contactMobile];
        storeInfoCell.storeAddressLabel.text = [UserInfo currentUser].contactAddr;
    }
    else if (indexPath.section == 1)
    {
        NSArray *arr = [[NSBundle mainBundle] loadNibNamed: @"SubmitOrderCell2" owner: nil options: nil];
        cell = [arr objectAtIndex: 0];
        
    }
     else   if (indexPath.section == 2)
    {
        
        if (indexPath.row == 0)
        {
            NSArray *arr = [[NSBundle mainBundle] loadNibNamed: @"SubmitOrderCell3" owner: nil options: nil];
            cell = [arr objectAtIndex: 0];
            
            SubmitOrderCell3 *cellListTitle = (SubmitOrderCell3 *)cell;
            cellListTitle.goodsNameLabel.text = @"费用清单";
        }
        else if (indexPath.row == self.orderInfoArray.count + 1)
        {
            NSArray *arr = [[NSBundle mainBundle] loadNibNamed: @"SubmitOrder4" owner: nil options: nil];
            cell = [arr objectAtIndex: 0];
            
            SubmitOrder4 *priceCell = (SubmitOrder4 *)cell;
            double totalPrice = [[MemoryData sharedMemoryData] getTotalPrice];

            priceCell.totalPriceLabel.text = [NSString stringWithFormat: @"￥%.2f", totalPrice];
            priceCell.carriagePriceLabel.text = @"￥0.0";
        }
        else if(indexPath.row > 0 && indexPath.row <self.orderInfoArray.count + 1)
        {
            static NSString *identifier = @"submitOrderCell3";
            cell = [tableView dequeueReusableCellWithIdentifier: identifier];
            
            if (!cell)
            {
                NSArray *arr = [[NSBundle mainBundle] loadNibNamed: @"SubmitOrderCell3" owner: nil options: nil];
                cell = [arr objectAtIndex: 0];
            }
            
            SubmitOrderCell3 *orderCell = (SubmitOrderCell3 *)cell;
            JFBOrderGoodsProductDS *orderInfo = self.orderInfoArray[indexPath.row - 1];
            
            orderCell.goodsNameLabel.text = orderInfo.merchantProductName;
            orderCell.goodsNumberLabel.text = [NSString stringWithFormat: @"X%ld", (long)orderInfo.buyCount];
            orderCell.goodsPriceLabel.text = [NSString stringWithFormat: @"￥%.2f", [orderInfo.productPrice floatValue]];
        }
    }
    
    [cell setSelectionStyle: UITableViewCellSelectionStyleNone];
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 2)
    {
        UIView *bgView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, self.view.frame.size.width, 50)];
        
        UITextField *beizhu = [[UITextField alloc] initWithFrame: CGRectMake(10, 10, self.view.frame.size.width - 20, 40)];
        beizhu.placeholder = @"如有备注，请留言说明";
        beizhu.layer.cornerRadius = 5;
        if ([beizhu.text isEqualToString:@""]) {
            self.beizhuStr = @"无";
        }else{
            beizhu.text = self.beizhuStr;
        }
        beizhu.font = [UIFont systemFontOfSize: 16];
        beizhu.backgroundColor = [UIColor whiteColor];
        beizhu.leftView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 10, beizhu.frame.size.height)];
        beizhu.delegate = self;
        [beizhu setLeftViewMode: UITextFieldViewModeAlways];
        
        [bgView addSubview: beizhu];
        
        return bgView;
    }
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (indexPath.section == 0) {
//        ChooseAddressController *addressVC = [[ChooseAddressController alloc]init];
//        addressVC.delegate = self;
//        [self.navigationController pushViewController: addressVC animated: YES];
//    }
//    if (indexPath.section == 2) {
//        SubmitOrderCell2 * cell = (SubmitOrderCell2 * )[tableView cellForRowAtIndexPath:indexPath];
//        InvoiceController *invoice = [[InvoiceController alloc]init];
//        invoice.text = cell.rightNameLabel.text;
//        invoice.delegate = self;
//        [self.navigationController pushViewController:invoice animated:YES];
//    }
}

-(void)invoiceInfo:(NSString *)info
{
    SubmitOrderCell2 *invoiceCell = (SubmitOrderCell2 *)[self.orderInfoTable cellForRowAtIndexPath: [NSIndexPath indexPathForRow: 0 inSection: 2]];
    invoiceCell.rightNameLabel.text = info;
    self.invoiceStr = info;
}

- (IBAction)submitOrderBtn:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    btn.enabled = false;
    
    NSDate *date = [NSDate date];
    NSDate *nextDate = [NSDate dateWithTimeInterval:24*60*60 sinceDate:date];
    NSDateFormatter *nowDate = [[NSDateFormatter alloc]init];
    [nowDate setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateTime = [nowDate stringFromDate:nextDate];
    
    NSMutableArray *shopSOItem = [NSMutableArray array];
    for (JFBOrderGoodsProductDS *goodsInfo in self.orderInfoArray) {
        NSDictionary *dic = @{@"merchantProductId":@(goodsInfo.merchantProductId),
                              @"merchantProductCode":[NSString stringWithFormat:@"%@",goodsInfo.merchantProductCode],
                              @"productId":@(goodsInfo.productId),
                              @"productCode":goodsInfo.productCode,
                              @"productName":goodsInfo.productName,
                              @"productSpec":goodsInfo.productSpec,
                              @"productPrice":goodsInfo.productPrice,
                              @"productBarcode":goodsInfo.productBarcode,
                              @"purchaseCount":@(goodsInfo.buyCount),
                              @"taxRate":@(goodsInfo.taxRate),
                              @"productCategoryId":@(goodsInfo.productCategoryId),
                              @"productCategoryName":goodsInfo.productCategoryName,
                              @"productBrandId":@(goodsInfo.productBrandId),
                              @"productBrandName":goodsInfo.productBrandName
                              };
        [shopSOItem addObject:dic];
    }
    NSData *data = [NSJSONSerialization dataWithJSONObject:shopSOItem options:0 error:NULL];
    NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//    
//    NSString *beizhu = [self.beizhuStr isEqualToString:@""]?0:self.beizhuStr;
    NSDictionary *shopInfo = @{@"ut":[UserInfo currentUser].ut,
                               @"merchantId":[UserInfo currentUser].merchantID,
                               @"merchantName":[UserInfo currentUser].shopkeeper,
                               @"warehouseId":[UserInfo currentUser].merchantID,
                               @"warehouseName":[UserInfo currentUser].shopkeeper,
                               @"supplierId":@(self.supplierId),
                               @"supplierName":self.supplierName,
                               @"supplierContactPerson":self.contactPerson,
                               @"supplierContactPhone":self.contactPhone,
                               @"deliveryType":@(1),
                               @"expectedArrivalDate":dateTime,
                               @"purchaseType":@(1),
                               @"note":self.beizhuStr,
                               @"payType":@(1),
                               @"createUserid":[UserInfo currentUser].merchantID,
                               @"createUsername":[UserInfo currentUser].shopkeeper,
                               @"purchaseEntriesDTOList":str,
                               };
    
    [JFBSubmitOrderDS submitOrder:^(JFBSubmitOrderDS *orderDetailInfo, NSError *error)
     {
         if(!error)
         {
             if (orderDetailInfo.resultCode == 0) {
                 [JFBUIAnimation alertTips:@"提交成功！"];
             }
             else {
                 [JFBUIAnimation alertTips:orderDetailInfo.message];
             }
             
            UIStoryboard *storyBoard = [UIStoryboard storyboardWithName: @"StoreManage"
                                                                 bundle: nil];
            OrderGoodsDetailController *orderDetailC = (OrderGoodsDetailController *)[storyBoard instantiateViewControllerWithIdentifier: @"orderGoodsDetailController"];
            orderDetailC.orderDetailInfo = orderDetailInfo;

            [self.navigationController pushViewController: orderDetailC animated: YES];
             
             // 清空购物车
             [[MemoryData sharedMemoryData].shoppingCarList removeAllObjects];
             
         }
         else
         {
             [JFBUIAnimation alertTips: @"提交订单失败"];
         }
         
         btn.enabled = YES;
    } shopInfo: shopInfo];
    
}

-(SelecctAddressDS *)getStoreInfo
{
    return self.addressModel;
}

-(void)setChooseAddress: (SelecctAddressDS *) addressInfo
{
    if (addressInfo)
    {
        self.addressModel.receiver = addressInfo.receiver;
        self.addressModel.receiver_phone = addressInfo.receiver_phone;
        self.addressModel.address_name = addressInfo.address_name;
        self.addressModel.ID = addressInfo.ID;
        [self.orderInfoTable reloadData];
    }
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    self.beizhuStr = textField.text;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    NSTimeInterval animationDuration=0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    
    [UIView setAnimationDuration:animationDuration];
    self.view.frame=CGRectMake(0, 0,self.view.frame.size.width, self.view.frame.size.height);
    
    return YES;
}

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    return YES;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect addStockRect = [textField convertRect: textField.frame toView: self.view];
    CGFloat offSet = self.view.frame.size.height - (CGRectGetMaxY(addStockRect) + 216 + 40);

    NSTimeInterval animationDuration=0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    
    [UIView setAnimationDuration:animationDuration];
    
    if(offSet < 0)
    {
        self.view.frame=CGRectMake(0, offSet,self.view.frame.size.width, self.view.frame.size.height);
        [UIView commitAnimations];
    }
}


@end
